package com.enjoyor.health.HGPT.service;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.enjoyor.health.HGPT.core.config.ParamConfig;
import com.enjoyor.health.HGPT.core.entity.Feedback;
import com.enjoyor.health.HGPT.core.entity.News;
import com.enjoyor.health.HGPT.core.entity.Policy;
import com.enjoyor.health.HGPT.core.entity.UserInfoMiniapp;
import com.enjoyor.health.HGPT.core.service.IFeedbackService;
import com.enjoyor.health.HGPT.core.service.INewsService;
import com.enjoyor.health.HGPT.core.service.IPolicyService;
import com.enjoyor.health.HGPT.core.service.IUserInfoMiniappService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Zhu Min
 * @date 2023/10/20 16:28
 */
@Service
public class BizNewsService {

    @Autowired
    private INewsService newsService;
    @Autowired
    private ParamConfig paramConfig;
    @Autowired
    private IPolicyService policyService;
    @Autowired
    private IUserInfoMiniappService userInfoMiniappService;
    @Autowired
    private IFeedbackService feedbackService;

    public JSONArray getDBMedicineNews(){
        List<News> newsList = newsService.getNewsList()
                .stream().filter(x-> !"0".equals(x.getStatus())).collect(Collectors.toList());
        JSONArray result = new JSONArray();
        for (News news : newsList) {
            JSONObject o = new JSONObject();
            o.put("title", news.getTitle());
            o.put("time", LocalDateTimeUtil.format(news.getTime(), "yyyy-MM-dd HH:mm:ss"));
            o.put("abstrct", news.getNewsAbstract());
            o.put("coverUrl", StringUtils.isNotBlank(news.getNewsCover())? paramConfig.getReportUrl() + news.getNewsCover() : null);
            o.put("id", news.getId());
            result.add(o);
        }
        return result;
    }

    public JSONObject getPolicyById(String policyId){
        JSONObject result = new JSONObject();
        Policy policy =  policyService.getById(policyId);
        if (policy != null){
            result.put("name", policy.getName());
            result.put("content", policy.getContent().replaceAll("\\r\\n", "\n").replaceAll("\\\\\\\\", "\\\\"));
        }
        return result;
    }

    public boolean insertDbFeedback(String title, String content, String openId){
        UserInfoMiniapp userInfoMiniapp = userInfoMiniappService.getUserInfoMiniappByOpenId(openId);
        if (StringUtils.isBlank(title)){
            title = "健康宝小程序-意见反馈";
        }
        LocalDateTime now = LocalDateTime.now();
        Feedback feedback = new Feedback();
        feedback.setId(IdUtil.simpleUUID());
        feedback.setOpinionTitle(title);
        feedback.setOpinionContent(content);
        feedback.setUserId(userInfoMiniapp==null?"null": userInfoMiniapp.getUserId());
        feedback.setStorageTime(now);
        feedback.setUpdateTime(now);
        return feedbackService.save(feedback);
    }

    public boolean insertDbFeedbackByApp(String userId, String title, String content){
        if (StringUtils.isBlank(title)){
            title = "健康宝APP-意见反馈";
        }
        LocalDateTime now = LocalDateTime.now();
        Feedback feedback = new Feedback();
        feedback.setId(IdUtil.simpleUUID());
        feedback.setOpinionTitle(title);
        feedback.setOpinionContent(content);
        feedback.setUserId(userId);
        feedback.setStorageTime(now);
        feedback.setUpdateTime(now);
        return feedbackService.save(feedback);
    }

    public JSONObject getNewsById(String newsId){
        News news = newsService.getById(newsId);
        JSONObject o = new JSONObject();
        if (news != null){
            JSONArray urlArray = new JSONArray();
            String url0 = StringUtils.isBlank(news.getUrlStart()) ? "" : paramConfig.getReportUrl() + news.getUrlStart();
            String url1 = StringUtils.isBlank(news.getUrlEnd()) ? "" : paramConfig.getReportUrl() + news.getUrlEnd();
            urlArray.add(url0);
            urlArray.add(url1);
            o.put("url", urlArray);
            if (StringUtils.isNotBlank(news.getContent())){
                String content = news.getContent().replaceAll("\\{host}", paramConfig.getReportUrl())
                        .replaceAll("\\r\\n", "\n")
                        .replaceAll("\\\\\\\\", "\\\\");
                o.put("content", content);
            }
            o.put("title", news.getTitle());
            o.put("time",LocalDateTimeUtil.format(news.getTime(), "yyyy-MM-dd HH:mm:ss"));
            o.put("author", news.getAuthor());
            o.put("source", news.getSource());
            o.put("likes", news.getLikes());
        }
        return o;
    }

    public void updateNewsLike(String newsId){
        newsService.updateNewsLike(newsId);
    }

    public Page<News> getNewsPage(String type, String status, String title, int page, int size){
        return newsService.getNewsPage(type, status, title, page, size);
    }

    public News getRawNewsById(String id){
        return newsService.getById(id);
    }

    public News addOrUpdateNews(News news){
        news.setEditTime(LocalDateTime.now());
        if (StringUtils.isBlank(news.getId())){
            news.setId(IdUtil.simpleUUID());
            news.setTime(LocalDateTime.now());
            news.setEditTime(LocalDateTime.now());
            news.setUp("0");
            news.setStatus("1");
            newsService.save(news);
        }else {
            news.setEditTime(LocalDateTime.now());
            newsService.updateById(news);
        }
        return news;
    }

    public News updateUp(String id){
        LocalDateTime now = LocalDateTime.now();
        News news = newsService.getById(id);
        if (news != null){
            String up = null;
            if (StringUtils.isNotBlank(news.getUp())){
                if ("0".equals(news.getUp())){
                    up="1";
                }else {
                    up="0";
                }
            }else {
                //为空，之前未置顶
                up = "1";
            }
            news.setUp(up);
            news.setEditTime(now);
            LambdaUpdateWrapper<News> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(News::getId, id)
                    .set(News::getEditTime, now)
                    .set(News::getUp, up);
            newsService.update(null, lambdaUpdateWrapper);
        }
        return news;
    }
    public News updateStatus(String id){
        LocalDateTime now = LocalDateTime.now();
        News news = newsService.getById(id);
        if (news != null){
            String status = null;
            if (StringUtils.isNotBlank(news.getStatus())){
                if ("1".equals(news.getStatus())){
                    status="0";
                }else {
                    status="1";
                }
            }else {
                //为空，之前未设置状态
                status = "0";
            }
            news.setStatus(status);
            news.setEditTime(now);
            LambdaUpdateWrapper<News> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(News::getId, id)
                    .set(News::getEditTime, now)
                    .set(News::getStatus, status);
            newsService.update(null, lambdaUpdateWrapper);
        }
        return news;
    }

}
